package account

import (
  "encoding/json"
  "fmt"
  . "gitee.com/yizhisamoye/GoWeChat/entity/user"
  "gitee.com/yizhisamoye/GoWeChat/utils"
  "net/http"
  "net/url"
)

/**
用户相关操作
 */
//生成跳转url
func(w WxAccount)GenerateAuthUrl(redirectUrl string,state string,isSilent bool)string{
  scope:="snsapi_userinfo"
  if isSilent{
    scope="snsapi_base"
  }
  redirectUrl=url.QueryEscape(redirectUrl)
  authUrl:=fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",w.appId,redirectUrl,scope,state)
  return authUrl
}
//生成处理授权跳转的handleFunc
func(w WxAccount)GenerateAuthHandleFunc(redirectUrl string,state string,isSilent bool)func(http.ResponseWriter,*http.Request){
  authUrl:=w.GenerateAuthUrl(redirectUrl,state,isSilent)
  fn:=func(writer http.ResponseWriter, request *http.Request) {
    http.Redirect(writer,request,authUrl,302)
  }
  return fn
}
//生成处理回调的handleFunc
func(w WxAccount)GenerateAuthRedirectHandleFunc(fn func(code,state string))func(http.ResponseWriter,*http.Request){
  resultFn:= func(writer http.ResponseWriter, request *http.Request) {
    request.ParseForm()
    code:=request.Form["code"][0]
    state:=request.Form["state"][0]
    fn(code,state)
  }
  return resultFn
}
//通过code获取用户accesstoken与openid
func(w WxAccount)GetUserAccessToken(code string)(map[string]interface{},error){
  url:=fmt.Sprintf(BaseUrl+"/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",w.appId,w.appSecret,code)
  resp,err:=http.Get(url)
  if err!=nil{
    return nil,err
  }
  return utils.CheckWxResp(resp)
}
//刷新accesstoken
func(w WxAccount)RefreshUserAccessToken(refreshToken string)(map[string]interface{},error){
  url:=fmt.Sprintf(BaseUrl+"/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s",w.appId,refreshToken)
  resp,err:=http.Get(url)
  if err!=nil{
    return nil,err
  }
  return utils.CheckWxResp(resp)
}
//检查token是否有效,
func(w WxAccount)CheckAccessTokenValidFromWxServer(accessToken ,openId string)error{
  url:=fmt.Sprintf(BaseUrl+"/sns/auth?access_token=%s&openid=%s",accessToken,openId)
  resp,err:=http.Get(url)
  if err!=nil{
    return err
  }
  _,err= utils.CheckWxResp(resp)
  return err
}
//拉取个人信息
func(w WxAccount)GetUserInfo(oauthToken string,query WxUserQuery)(*WxUser,error){
  dataLang:="zh_CN"
  openId:=query.OpenId
  if query.Lang!=""{
    dataLang=query.Lang
  }
  url:=fmt.Sprintf(BaseUrl+"/sns/userinfo?access_token=%s&openid=%s&lang=%s",oauthToken,openId,dataLang)
  resp,err:=http.Get(url)
  if err!=nil{
    return nil,err
  }
  result,err:= utils.CheckWxResp(resp)
  if err!=nil{
    return nil,err
  }
  resultBytes,err:=json.Marshal(result)
  if err!=nil{
    return nil,err
  }
  user:=new(WxUser)
  err=json.Unmarshal(resultBytes,user)
  if err!=nil{
    return nil,err
  }
  return user,nil
}
//批量获取用户信息
func(w WxAccount)GetUserInfoBatch(query []WxUserQuery)([]WxUser,error){
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/user/info/batchget?access_token=%s",w.accessToken)
  data:=make(map[string]interface{})
  data["user_list"]=query
  result,err:=utils.SendJson(url,data)
  if err!=nil{
    return nil,err
  }
  userInfoList:=result["user_info_list"].([]interface{})
  userList:=make([]WxUser,0)
  for _,v:=range userInfoList{
    user:=new(WxUser)
    temp,_:=json.Marshal(v)
    json.Unmarshal(temp,user)
    userList=append(userList,*user)
  }
  return userList,nil
}
//获取关注用户列表
func(w WxAccount)GetSubscribeUser(nextOpenId ...string)(map[string]interface{},error){
  next:=""
  if len(nextOpenId)>0{
    next=nextOpenId[0]
  }
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/user/get?access_token=%s&next_openid=%s",w.accessToken,next)
  resp,err:=http.Get(url)
  if err!=nil{
    return nil,err
  }
  return utils.CheckWxResp(resp)
}
//设置用户备注
func(w WxAccount)RemarkUser(user WxUser)error{
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/user/info/updateremark?access_token=%s",w.accessToken)
  _,err:=utils.SendJson(url,map[string]string{
    "openid":user.OpenId,
    "remark":user.Remark,
  })
  return err
}
